package com.sjc.algorithm.interview;

import java.util.Arrays;

/**
 * 2个51位整数相加
 * @author by SangJiacun
 * @Date 2020/5/14 11:56
 */
public class BigIntAdd {
    public static void main(String[] args) {
        System.out.println(bigNumberSum("426709752318", "95481253129"));
    }

    private static String bigNumberSum(String num1, String num2){
        int length = num1.length()>num2.length()?num1.length():num2.length();
        length = length+1;

        int[] num1Arr = new int[length];
        for(int i=0; i< num1.length(); i++){
            num1Arr[i] = num1.charAt(num1.length()-1-i)-'0';
        }
        System.out.println(Arrays.toString(num1Arr));

        int[] num2Arr = new int[length];
        for(int i=0; i< num2.length(); i++){
            num2Arr[i] = num2.charAt(num2.length()-1-i)-'0';
        }
        System.out.println(Arrays.toString(num2Arr));

        int[] result = new int[length];
        for(int i=0;i<length;i++){
            if(result[i] + num1Arr[i] + num2Arr[i] >= 10){
                result[i+1] = 1;
                result[i] = (result[i] + num1Arr[i] + num2Arr[i])%10;
            }else{
                result[i] = result[i] + num1Arr[i] + num2Arr[i];
            }
        }

        System.out.println(Arrays.toString(result));

        StringBuilder sb = new StringBuilder();
        for(int i=length-1; i>=0;i--){
            sb.append(result[i]);
        }
        String sum = sb.toString();
        if(sum.startsWith("0")){
            sum = sum.substring(1,sum.length());
        }
        return sum;
    }
}
